package cn.yangyumanage;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.yangyumanage.application.DataApplication;
import cn.yangyumanage.bean.EpisodeUrl;
import cn.yangyumanage.bean.Film;
import cn.yangyumanage.bean.FilmUrl;
import cn.yangyumanage.bean.ImageQuality;
import cn.yangyumanage.bean.LargeClassification;
import cn.yangyumanage.bean.SmallClassification;
import cn.yangyumanage.bean.TheRegion;
import cn.yangyumanage.bean.TheYear;
import cn.yangyumanage.callback.DataCallBack;
import cn.yangyumanage.http.HttpClient;
import cn.yangyumanage.model.EditHttpModel;
import cn.yangyumanage.util.ToastUtil;
import cn.yangyumanage.util.Utils;

public class EditActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_back;
    private EditText et_film_name;
    private EditText et_pinyin_name;
    private EditText et_post_url;
    private EditText et_score;
    private EditText et_release_date;
    private EditText et_play_num;
    private EditText et_single_episode_length;
    private EditText et_production_country_or_region;
    private EditText et_tag;
    private EditText et_director;
    private EditText et_scriptwriter;
    private EditText et_leading_role;
    private EditText et_language;
    private EditText et_premiere;
    private EditText et_number_of_seasons;
    private EditText et_number_of_episode;
    private EditText et_aka;
    private EditText et_plot;
    private Spinner sp_large_classification;
    private Spinner sp_small_classification;
    private Spinner sp_the_year;
    private Spinner sp_the_region;
    private final EditHttpModel httpModel = new EditHttpModel();
    private Spinner sp_image_quality;
    private ArrayAdapter<String> arrayAdapter;
    private LinearLayout ll_url_item_add;
    private LinearLayout ll_item_store;
    private ArrayList<Spinner> spinners = new ArrayList<>();
    private ArrayList<EditText> editTexts = new ArrayList<>();
    private EditText et_url_qianbu;
    private EditText et_url_weibu;
    private EditText et_film_url;
    private LinearLayout ll_url_quick_add;
    private Film film;
    private List<FilmUrl> filmUrls;
    private FilmUrl filmUrl;
    private LinearLayout ll_save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        initView();
        initData();
    }

    //设置状态栏
    private void statusBarSetting() {
        Window window = getWindow();
        //设置状态栏颜色为透明
        window.setStatusBarColor(getResources().getColor(R.color.white, null));
        //设置状态栏字体颜色自行改变
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    private void initView() {
        statusBarSetting();
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        et_film_name = findViewById(R.id.et_film_name);
        et_pinyin_name = findViewById(R.id.et_pinyin_name);
        et_post_url = findViewById(R.id.et_post_url);
        et_score = findViewById(R.id.et_score);
        et_release_date = findViewById(R.id.et_release_date);
        et_play_num = findViewById(R.id.et_play_num);
        et_single_episode_length = findViewById(R.id.et_single_episode_length);
        et_production_country_or_region = findViewById(R.id.et_production_country_or_region);
        sp_large_classification = findViewById(R.id.sp_large_classification);
        sp_small_classification = findViewById(R.id.sp_small_classification);
        sp_the_year = findViewById(R.id.sp_the_year);
        sp_the_region = findViewById(R.id.sp_the_region);
        et_tag = findViewById(R.id.et_tag);
        et_director = findViewById(R.id.et_director);
        et_scriptwriter = findViewById(R.id.et_scriptwriter);
        et_leading_role = findViewById(R.id.et_leading_role);
        et_language = findViewById(R.id.et_language);
        et_premiere = findViewById(R.id.et_premiere);
        et_number_of_seasons = findViewById(R.id.et_number_of_seasons);
        et_number_of_episode = findViewById(R.id.et_number_of_episode);
        et_aka = findViewById(R.id.et_aka);
        et_plot = findViewById(R.id.et_plot);
        sp_image_quality = findViewById(R.id.sp_image_quality);
        ll_url_item_add = findViewById(R.id.ll_url_item_add);
        ll_item_store = findViewById(R.id.ll_item_store);
        ll_url_item_add.setOnClickListener(this);
        et_url_qianbu = findViewById(R.id.et_url_qianbu);
        et_url_weibu = findViewById(R.id.et_url_weibu);
        et_film_url = findViewById(R.id.et_film_url);
        ll_url_quick_add = findViewById(R.id.ll_url_quick_add);
        ll_url_quick_add.setOnClickListener(this);
        ll_save = findViewById(R.id.ll_save);
        ll_save.setOnClickListener(this);
    }

    private void initData() {
        getAllLarge();
        getAllImageQuality();
        Bundle bundle = getIntent().getExtras();
        film = (Film) bundle.getSerializable("filmBean");
        String filmUrlJson = film.getFilmUrl();
        try {
            filmUrls = DataApplication.gson.fromJson(filmUrlJson, new TypeToken<List<FilmUrl>>() {
            }.getType());
            filmUrl = filmUrls.get(0);
        } catch (Exception e) {
            ToastUtil.show(this, "影片地址异常");
            List<EpisodeUrl> urlList = new ArrayList<>();
            EpisodeUrl episodeUrl = new EpisodeUrl("异常", "影片地址异常，请重新添加！");
            urlList.add(episodeUrl);
            filmUrl = new FilmUrl("异常", urlList);
        }
        et_film_name.setText(film.getName());
        et_pinyin_name.setText(film.getPinYinName());
        et_post_url.setText(film.getPostUrl());
        et_score.setText(film.getScore());
        et_release_date.setText(film.getReleaseDate());
        et_play_num.setText(String.valueOf(film.getPlayNum()));
        et_single_episode_length.setText(film.getSingleEpisodeLength());
        et_production_country_or_region.setText(film.getProductionCountryOrRegion());
        et_tag.setText(film.getTag());
        et_director.setText(film.getDirector());
        et_scriptwriter.setText(film.getScriptwriter());
        et_leading_role.setText(film.getLeadingRole());
        et_language.setText(film.getLanguage());
        et_premiere.setText(film.getPremiere());
        et_number_of_seasons.setText(String.valueOf(film.getNumberOfSeasons()));
        et_number_of_episode.setText(String.valueOf(film.getNumberOfEpisode()));
        et_aka.setText(film.getAka());
        et_plot.setText(film.getPlot());
        List<EpisodeUrl> url = filmUrl.getUrl();
        if (film.getLargeClassification().equals("电影")) {
            EpisodeUrl episodeUrl = url.get(0);
            et_film_url.setText(episodeUrl.getUrl());
        } else {
            String urlJson = DataApplication.gson.toJson(url);
            et_film_url.setText(urlJson);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_save:
                if (et_film_name.getText().toString().equals("")) {
                    ToastUtil.show(this, "影片名称不能为空哦");
                } else {
                    if (et_film_url.getText().toString().equals("")) {
                        ToastUtil.show(this, "影片地址不能为空哦");
                    } else {
                        film.setName(et_film_name.getText().toString());
                        film.setPinYinName(et_pinyin_name.getText().toString());
                        film.setPostUrl(et_post_url.getText().toString());
                        film.setScore(et_score.getText().toString());
                        film.setReleaseDate(et_release_date.getText().toString());
                        film.setPlayNum(Integer.valueOf(et_play_num.getText().toString()));
                        film.setSingleEpisodeLength(et_single_episode_length.getText().toString());
                        film.setProductionCountryOrRegion(et_production_country_or_region.getText().toString());
                        if (sp_large_classification.getSelectedItemPosition() != -1) {
                            film.setLargeClassification(sp_large_classification.getSelectedItem().toString());
                        }
                        if (sp_small_classification.getSelectedItemPosition() != -1) {
                            film.setSmallClassification(sp_small_classification.getSelectedItem().toString());
                        }
                        if (sp_the_region.getSelectedItemPosition() != -1) {
                            film.setTheRegion(sp_the_region.getSelectedItem().toString());
                        }
                        if (sp_the_year.getSelectedItemPosition() != -1) {
                            film.setTheYear(sp_the_year.getSelectedItem().toString());
                        }
                        film.setTag(et_tag.getText().toString());
                        film.setDirector(et_director.getText().toString());
                        film.setScriptwriter(et_scriptwriter.getText().toString());
                        film.setLeadingRole(et_leading_role.getText().toString());
                        film.setLanguage(et_language.getText().toString());
                        film.setPremiere(et_premiere.getText().toString());
                        film.setNumberOfSeasons(et_number_of_seasons.getText().toString());
                        film.setNumberOfEpisode(et_number_of_episode.getText().toString());
                        film.setAka(et_aka.getText().toString());
                        film.setPlot(et_plot.getText().toString());
                        List<FilmUrl> filmUrlList = new ArrayList<>();
                        if (sp_image_quality.getSelectedItemPosition() != -1) {
                            if (sp_large_classification.getSelectedItemPosition() != -1) {
                                String largeClassfication = sp_large_classification.getSelectedItem().toString();
                                if (!largeClassfication.equals("电影")) {
                                    Type listOfMyClassObject = new TypeToken<ArrayList<EpisodeUrl>>() {
                                    }.getType();
                                    try {
                                        List<EpisodeUrl> outputList = DataApplication.gson.fromJson(et_film_url.getText().toString(), listOfMyClassObject);
                                        FilmUrl filmUrl = new FilmUrl(sp_image_quality.getSelectedItem().toString(), outputList);
                                        filmUrlList.add(filmUrl);
                                    } catch (Exception e) {
                                        ToastUtil.show(this, "影片地址不符合规范！");
                                        return;
                                    }
                                } else {
                                    EpisodeUrl episodeUrl = new EpisodeUrl(sp_image_quality.getSelectedItem().toString(), et_film_url.getText().toString());
                                    List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                                    episodeUrlList.add(episodeUrl);
                                    FilmUrl filmUrl = new FilmUrl(sp_image_quality.getSelectedItem().toString(), episodeUrlList);
                                    filmUrlList.add(filmUrl);
                                }
                            }
                        }

                        for (int i = 0; i < spinners.size(); i++) {
                            if (spinners.get(i).getSelectedItemPosition() != -1) {
                                if (editTexts.get(i).getText().toString().equals("")) {
                                    ToastUtil.show(this, "影片地址不能为空哦");
                                    return;
                                } else {
                                    if (sp_large_classification.getSelectedItemPosition() != -1) {
                                        String largeClassfication = sp_large_classification.getSelectedItem().toString();
                                        if (!largeClassfication.equals("电影")) {
                                            Type listOfMyClassObject = new TypeToken<ArrayList<EpisodeUrl>>() {
                                            }.getType();
                                            try {
                                                List<EpisodeUrl> outputList = DataApplication.gson.fromJson(editTexts.get(i).getText().toString(), listOfMyClassObject);
                                                FilmUrl filmUrl = new FilmUrl(spinners.get(i).getSelectedItem().toString(), outputList);
                                                filmUrlList.add(filmUrl);
                                            } catch (Exception e) {
                                                ToastUtil.show(this, "影片地址不符合规范！");
                                                return;
                                            }

                                        } else {
                                            EpisodeUrl episodeUrl = new EpisodeUrl(spinners.get(i).getSelectedItem().toString(), editTexts.get(i).getText().toString());
                                            List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                                            episodeUrlList.add(episodeUrl);
                                            FilmUrl filmUrl = new FilmUrl(spinners.get(i).getSelectedItem().toString(), episodeUrlList);
                                            filmUrlList.add(filmUrl);
                                        }
                                    }
                                }
                            }
                        }

                        String filmUrlJson = DataApplication.gson.toJson(filmUrlList);
                        film.setFilmUrl(filmUrlJson);
                        httpModel.updateFilmById(film, new DataCallBack() {
                            @Override
                            public void getData(Object data) {
                                Boolean flag = (Boolean) data;
                                HttpClient.handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (flag) {
                                            ToastUtil.show(EditActivity.this, "保存成功");
                                            DataApplication.dataFlag = false;
                                            finish();
                                        } else {
                                            ToastUtil.show(EditActivity.this, "保存失败");
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_url_quick_add:
                String numberOfEpisode = et_number_of_episode.getText().toString();
                String urlQianbu = et_url_qianbu.getText().toString();
                String urlWeibu = et_url_weibu.getText().toString();
                if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                    int episodeNum = Integer.parseInt(numberOfEpisode);
                    List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                    for (int i = 1; i < episodeNum + 1; i++) {
                        String url = urlQianbu + i + urlWeibu;
                        String episode = i + "";
                        EpisodeUrl episodeUrl = new EpisodeUrl(episode, url);
                        episodeUrlList.add(episodeUrl);
                    }
                    String episodeJson = DataApplication.gson.toJson(episodeUrlList);
                    et_film_url.setText(episodeJson);
                }
                break;
            case R.id.ll_url_item_add:
                View customView = LayoutInflater.from(this).inflate(R.layout.film_url_add_item, ll_item_store, false);

                Spinner sp_image_quality_item = customView.findViewById(R.id.sp_image_quality_item);
                sp_image_quality_item.setAdapter(arrayAdapter);
                sp_image_quality_item.setSelection(0);

                EditText et_film_url_item = customView.findViewById(R.id.et_film_url_item);
                EditText et_url_qianbu_item = customView.findViewById(R.id.et_url_qianbu_item);
                EditText et_url_weibu_item = customView.findViewById(R.id.et_url_weibu_item);
                LinearLayout ll_url_quick_add_item = customView.findViewById(R.id.ll_url_quick_add_item);

                ll_item_store.addView(customView);
                spinners.add(sp_image_quality_item);
                editTexts.add(et_film_url_item);

                ll_url_quick_add_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String numberOfEpisode = et_number_of_episode.getText().toString();
                        String urlQianbu = et_url_qianbu_item.getText().toString();
                        String urlWeibu = et_url_weibu_item.getText().toString();
                        if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                            int episodeNum = Integer.parseInt(numberOfEpisode);
                            List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                            for (int i = 1; i < episodeNum + 1; i++) {
                                String url = urlQianbu + i + urlWeibu;
                                String episode = i + "";
                                EpisodeUrl episodeUrl = new EpisodeUrl(episode, url);
                                episodeUrlList.add(episodeUrl);
                            }
                            String episodeJson = DataApplication.gson.toJson(episodeUrlList);
                            et_film_url_item.setText(episodeJson);
                        }
                    }
                });

                LinearLayout ll_delete = customView.findViewById(R.id.ll_delete);
                ll_delete.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int index = ll_item_store.indexOfChild(customView);
                        ll_item_store.removeView(ll_item_store.getChildAt(index));
                        spinners.remove(index - 1);
                        editTexts.remove(index - 1);
                        return true;
                    }
                });
                break;
        }
    }

    //item add
    private void urlItemAdd(FilmUrl filmUrl, List<String> imageQualityList) {
        View customView = LayoutInflater.from(this).inflate(R.layout.film_url_add_item, ll_item_store, false);

        Spinner sp_image_quality_item = customView.findViewById(R.id.sp_image_quality_item);
        sp_image_quality_item.setAdapter(arrayAdapter);
        sp_image_quality_item.setSelection(imageQualityList.indexOf(filmUrl.getImageQuality()));

        EditText et_film_url_item = customView.findViewById(R.id.et_film_url_item);
        if (film.getLargeClassification().equals("电影")) {
            EpisodeUrl episodeUrl = filmUrl.getUrl().get(0);
            et_film_url_item.setText(episodeUrl.getUrl());
        } else {
            String urlJson = DataApplication.gson.toJson(filmUrl.getUrl());
            et_film_url_item.setText(urlJson);
        }
        EditText et_url_qianbu_item = customView.findViewById(R.id.et_url_qianbu_item);
        EditText et_url_weibu_item = customView.findViewById(R.id.et_url_weibu_item);
        LinearLayout ll_url_quick_add_item = customView.findViewById(R.id.ll_url_quick_add_item);

        ll_item_store.addView(customView);
        spinners.add(sp_image_quality_item);
        editTexts.add(et_film_url_item);

        ll_url_quick_add_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String numberOfEpisode = et_number_of_episode.getText().toString();
                String urlQianbu = et_url_qianbu_item.getText().toString();
                String urlWeibu = et_url_weibu_item.getText().toString();
                if (!numberOfEpisode.equals("") && !urlQianbu.equals("") && !urlWeibu.equals("")) {
                    int episodeNum = Integer.parseInt(numberOfEpisode);
                    List<EpisodeUrl> episodeUrlList = new ArrayList<>();
                    for (int i = 1; i < episodeNum + 1; i++) {
                        String url = urlQianbu + i + urlWeibu;
                        String episode = i + "";
                        EpisodeUrl episodeUrl = new EpisodeUrl(episode, url);
                        episodeUrlList.add(episodeUrl);
                    }
                    String episodeJson = DataApplication.gson.toJson(episodeUrlList);
                    et_film_url_item.setText(episodeJson);
                }
            }
        });

        LinearLayout ll_delete = customView.findViewById(R.id.ll_delete);
        ll_delete.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int index = ll_item_store.indexOfChild(customView);
                ll_item_store.removeView(ll_item_store.getChildAt(index));
                spinners.remove(index - 1);
                editTexts.remove(index - 1);
                return true;
            }
        });
    }

    //获取所有大分类
    private void getAllLarge() {
        httpModel.getAllLarge(new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<LargeClassification> datas = Utils.<LargeClassification>objectToList(data);
                List<String> largeClassificationList = new ArrayList<>();
                for (LargeClassification largeClassification : datas) {
                    largeClassificationList.add(largeClassification.getClassification());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(EditActivity.this, R.layout.item_select, largeClassificationList);
                        sp_large_classification.setAdapter(arrayAdapter);
                        sp_large_classification.setSelection(largeClassificationList.indexOf(film.getLargeClassification()));
                        sp_large_classification.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                getAllRelatedSmallClassification(datas.get(position).getId());
                                getAllRelatedRegion(datas.get(position).getId());
                                getAllRelatedYear(datas.get(position).getId());
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                    }
                });

            }
        });
    }

    //获取指定大分类id所关联的所有小分类
    public void getAllRelatedSmallClassification(int id) {
        httpModel.getAllRelatedSmallClassification(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<SmallClassification> datas = Utils.<SmallClassification>objectToList(data);
                List<String> smallClassificationList = new ArrayList<>();
                for (SmallClassification smallClassification : datas) {
                    smallClassificationList.add(smallClassification.getClassification());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(EditActivity.this, R.layout.item_select, smallClassificationList);
                        sp_small_classification.setAdapter(arrayAdapter);
                        sp_small_classification.setSelection(smallClassificationList.indexOf(film.getSmallClassification()));
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                    }
                });
            }
        });
    }

    //获取指定大分类id所关联的所有地区
    public void getAllRelatedRegion(int id) {
        httpModel.getAllRelatedRegion(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<TheRegion> datas = Utils.<TheRegion>objectToList(data);
                List<String> theRegionList = new ArrayList<>();
                for (TheRegion theRegion : datas) {
                    theRegionList.add(theRegion.getTheRegion());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(EditActivity.this, R.layout.item_select, theRegionList);
                        sp_the_region.setAdapter(arrayAdapter);
                        sp_the_region.setSelection(theRegionList.indexOf(film.getTheRegion()));
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                    }
                });
            }
        });
    }

    //获取指定大分类id所关联的所有年份
    public void getAllRelatedYear(int id) {
        httpModel.getAllRelatedYear(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                List<TheYear> datas = Utils.<TheYear>objectToList(data);
                List<String> theYearList = new ArrayList<>();
                for (TheYear theYear : datas) {
                    theYearList.add(theYear.getTheYear());
                }
                HttpClient.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(EditActivity.this, R.layout.item_select, theYearList);
                        sp_the_year.setAdapter(arrayAdapter);
                        sp_the_year.setSelection(theYearList.indexOf(film.getTheYear()));
                        arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                    }
                });
            }
        });
    }

    //获取全部画质信息
    private void getAllImageQuality() {
        httpModel.getAllImageQuality(data -> {
            List<ImageQuality> datas = Utils.<ImageQuality>objectToList(data);
            List<String> imageQualityList = new ArrayList<>();
            for (ImageQuality imageQuality : datas) {
                imageQualityList.add(imageQuality.getImageQuality());
            }
            HttpClient.handler.post(() -> {
                arrayAdapter = new ArrayAdapter<>(EditActivity.this, R.layout.item_select, imageQualityList);
                sp_image_quality.setAdapter(arrayAdapter);
                sp_image_quality.setSelection(imageQualityList.indexOf(filmUrl.getImageQuality()));
                arrayAdapter.setDropDownViewResource(R.layout.item_dropdown);
                if (filmUrls != null) {
                    for (int i = 0; i < filmUrls.size(); i++) {
                        if (i != 0) {
                            urlItemAdd(filmUrls.get(i), imageQualityList);
                        }
                    }
                }
            });
        });
    }
}